/**
 * @Description: Mr请求指令
 * @author Beon
 * @date 2021/1/25
*/
import {OraLoading} from '../decorators/oraLoading';
import {ClassTool} from '../decorators/classTool';
import {GitLabInquirer} from '../inquirer/gitLabInquirer';
import {BranchOrigin} from '../git/branchOrigin';

export class LzMr {
    @OraLoading.beProxy
    status: OraLoading // 执行状态
    static reg = new RegExp('.*://[^/]*')

    constructor() {
        this.status.value = 'mr前处理';
    }

    /**
     * 指令运行函数
     * @param {[String]} arg 参数
     * @returns {Promise<void>}
     */
    @ClassTool.saveThis
    async done(arg?: [string]): Promise<void> {
        await LzMr.infoDeal(arg ? arg[0] : undefined);

        let index = 0;
        while (index < BranchOrigin.Origins.length) {
            await GitLabInquirer.checkLabInquirer(BranchOrigin.Origins[index].match(LzMr.reg)[0]);

            this.status.value = `准备${BranchOrigin.Origins[index]}远程库Mr信息`;
            await LzMr.mrDeal(BranchOrigin.Origins[index], this.status);
            index++;
        }

        this.status.value = '';
    }


    /**
     * 远端库信息处理
     * @param repoPath
     * @returns {Promise<void>}
     */
    static async infoDeal(repoPath?: string): Promise<void> {
        await BranchOrigin.dealOriginUrlMessage(repoPath);
    }

    /**
     * 处理mr提交
     * @param origin
     * @param status
     * @returns {Promise<void>}
     * @param url
     */
    static async mrDeal(origin:string, status: OraLoading): Promise<void> {
        const url = origin.match(LzMr.reg)[0];
        await GitLabInquirer.dealLabInquirer(origin, url);

        status.value = `开始提交${origin}远程库Mr信息`;

        await BranchOrigin.dealBranchMessage();

        console.log(`当前分支为：${BranchOrigin.gitBranch}（为确保操作准确性，只允许在当前分支发起mr请求）\n`.warning);

        const response = await GitLabInquirer.gitlabInquirer(url) as {'web_url': string};
        console.log(`创建成功!访问地址为：${response.web_url.replace(response.web_url.match(LzMr.reg)[0], origin.match(LzMr.reg)[0])}\n`.info);
    }
}
